/**
 * 
 */
package com.planner.core.action.node.file;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.planner.core.action.node.form.MultipleNodeDetailsForm;
import com.planner.core.action.node.form.NodeDetailForm;
import com.planner.core.action.node.util.NodeDetailFormUtil;
import com.planner.core.vo.GraphNode;

/**
 * @author Sangharsh
 *
 */
public class ProcessNodeFileAction extends AbstractNodeFileAction {
	
	private static final Log LOG = LogFactory.getLog(ProcessNodeFileAction.class);

	
	/* (non-Javadoc)
	 * @see com.planner.core.action.core.AbstractBaseAction#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		MultipleNodeDetailsForm detailsForm = (MultipleNodeDetailsForm)form;
		LOG.info("Processing Nodes ");
		Set<String> existingNodes = getExistingNodeCodes();
		List<GraphNode> nodes = new ArrayList<GraphNode>();
		for(NodeDetailForm detailForm : detailsForm.getNodes()){
			if(detailForm!=null){
				if(!existingNodes.contains(detailForm.getCode())){
					nodes.add(NodeDetailFormUtil.getNodeVOFromForm(detailForm));
				}else{
					LOG.info(detailForm+" already exist");
				}
			}
		}
		stopService.addAll(nodes);	
		
		return mapping.findForward(SUCCESS_FORWARD);
	}
	private Set<String> getExistingNodeCodes(){
		Set<String> nodes = new HashSet<String>();
		List<GraphNode> existingNodes =stopService.getAllNodes();
		for(GraphNode node : existingNodes){
			nodes.add(node.getCode());
		}
		return nodes;
	}
}
